<template>
  <div>
    <!-- 面包屑导航视图 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card视图区域 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert title="注意: 只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false"> </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="select_params">
        <el-col>
          <span>选择商品分类: </span>
          <!-- 选择商品的级联选择器 -->
          <el-cascader v-model="parentKeys" :options="cateList" :props="CateProps" @change="cateParamsChanged" class="cascader_cate" clearable></el-cascader>
        </el-col>
      </el-row>

      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleCateClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button type="primary" size="mini" :disabled="isBtnVisible" @click="addParamsVisible = true">添加参数</el-button>
          <!-- 动态参数table表格视图 -->
          <el-table :data="manyCateData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染的tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="deleteTag(i, scope.row)"> {{ item }} </el-tag>
                <!-- input 文本输入 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCateParams(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnVisible" @click="addParamsVisible = true">添加属性</el-button>
          <!-- 静态属性的table表格视图 -->
          <el-table :data="onlyCateData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染的tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="deleteTag(i, scope.row)"> {{ item }} </el-tag>
                <!-- input 文本输入 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCateParams(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加按钮的dialog视图 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addParamsVisible" width="50%" @close="addDialogClose">
      <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑商品的弹出视图 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editParamsVisible" width="50%" @close="editParamsClose">
      <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 存储商品分类的数组
      cateList: [],
      // 级联选择器的双向绑定的数组
      parentKeys: [],
      // 级联选择器的设置
      CateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // tab 页签当前的显示的name值
      activeName: 'many',
      // 动态参数
      manyCateData: [],
      // 静态参数
      onlyCateData: [],
      // 控制添加参数的对话框的显示与隐藏
      addParamsVisible: false,
      // 添加参数的form表单数据
      addParamsForm: {
        attr_name: ''
      },
      // 添加表达的效验
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 修改参数的显示与隐藏
      editParamsVisible: false,
      // 修改表单的数据对象
      editParamsForm: {},
      // 修改表单的验证规则
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 控制文本和按钮切换的开关,默认显示按钮
      inputVisible: false,
      // 文本输入的内容数据
      inputValue: ''
    }
  },
  created() {
    this.getCateLists()
  },
  methods: {
    // 获取分类列表
    async getCateLists() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类数据失败')
      this.cateList = res.data
    },
    // 级联选择器改变后触发的函数，
    cateParamsChanged() {
      this.getCateData()
    },
    // 监听页签的切换函数
    handleCateClick() {
      this.getCateData()
      console.log(this.activeName)
    },
    // 获取参数列表数据
    async getCateData() {
      // 1.纠正用户不选择三级分类
      if (this.parentKeys.length !== 3) {
        this.parentKeys = []
        this.manyCateData = []
        this.onlyCateData = []
        return
      }
      // 2.获取参数列表
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      // 在取出数据之前将 attr_vals 从字符串转变为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      // 判断数据是动态参数数据还是静态参数数据
      if (this.activeName === 'many') {
        this.manyCateData = res.data
        console.log(this.manyCateData)
      } else {
        this.onlyCateData = res.data
        console.log(this.onlyCateData)
      }
    },
    // 添加动态或者静态属性
    addParams() {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.getCateData()
        this.addParamsVisible = false
        this.$message.success('添加参数成功')
      })
    },
    // 监听添加参数对话框的关闭
    addDialogClose() {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 监听修改参数对话框的关闭
    editParamsClose() {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 点击修改按钮展示对话框
    async editCateParams(id) {
      // 查询当前要修改的参数的数据
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.editParamsForm = res.data
      this.$message.success('获取数据成功')
      this.editParamsVisible = true
    },
    // 点击确定按钮关闭会话框,完成修改参数请求
    async editParams() {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, { attr_name: this.editParamsForm.attr_name, attr_sel: this.activeName })
      if (res.meta.status !== 200) return this.$message.error('修改参数失败')
      this.$message.success('修改参数成功')
      this.getCateData()
      this.editParamsVisible = false
    },
    // 删除参数的函数
    async removeParams(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已经取消删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.getCateData()
      this.$message.success('删除参数成功')
    },
    // 键盘enter按下和失去焦点触发的函数
    async handleInputConfirm(info) {
      // 项目优化如果用户输入的内容为空格那么就清空文本
      // trim() 函数是去除文本前后的空格的函数
      if (info.inputValue.trim().length === 0) {
        info.inputValue = ''
        // 当按钮 enter 和文本失去焦点的时候显示按钮
        info.inputVisible = false
        return
      }
      // 如果没有return 就做后续的处理
      // 前端的数据添加
      info.attr_vals.push(info.inputValue.trim())
      info.inputValue = ''
      info.inputVisible = false
      // 提交数据
      this.editAttrVals(info)
    },
    // 将后端数据库的提交单独抽离出来
    async editAttrVals(info) {
      // 将对 attr_vals 的操作保存到后端的数据
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${info.attr_id}`, {
        attr_name: info.attr_name,
        attr_sel: info.attr_sel,
        // 这里需要先将attr_vals拼接成字符串
        attr_vals: info.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('添加新属性失败')
      this.getCateData()
      return this.$message.success('添加新属性成功')
    },
    // 切换input 和 按钮 显示的处理函数
    showInput(info) {
      info.inputVisible = true
      // 点击按钮自动获取焦点
      //  $nextTick 是在页面重新渲染的时候触发里面的函数的
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除标签的处理函数
    async deleteTag(index, info) {
      info.attr_vals.splice(index, 1)
      // 提交数据
      this.editAttrVals(info)
    }
  },
  computed: {
    // 编写一个计算属性来动态的启用和禁用
    isBtnVisible() {
      if (this.parentKeys.length !== 3) {
        return true
      }
      return false
    },
    // 请求参数列表的属性的id值
    cateId() {
      if (this.parentKeys.length === 3) {
        return this.parentKeys[2]
      }
      return null
    },
    // title的计算属性函数
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.select_params {
  margin: 15px 0;
}
.cascader_cate {
  width: 260px;
}
.el-tag {
  margin: 0 10px;
}

.input-new-tag {
  width: 150px;
}
</style>
